package com.navi168.fwq21.hyzl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.amap.mapapi.core.AMapException;
import com.amap.mapapi.core.GeoPoint;
import com.amap.mapapi.core.PoiItem;
import com.amap.mapapi.poisearch.PoiPagedResult;
import com.amap.mapapi.poisearch.PoiSearch;
import com.amap.mapapi.poisearch.PoiTypeDef;
import com.amap.mapapi.poisearch.PoiSearch.SearchBound;
import com.navi168.fwq21.R;
import com.navi168.fwq21.db.Sqlh;
import com.navi168.fwq21.hyzl.mod.Favo;
import com.navi168.fwq21.hyzl.mod.MypoiItems;
import com.navi168.fwq21.util.SendPosition;
import com.navi168.fwq21.util.Tools;

public class PoiList extends Activity {
	private final String SPF = "NAVI168";
	private ListView poiListView;
	private Button previous_but;
	private Button next_but;
	private PoiPagedResult result;
	private String poiString = "";
	private String classname = "";
	private ProgressDialog progDialog;
	private Context context;
	private List<PoiItem> poiItems = new ArrayList<PoiItem>();
	private MyAdapter mAdapter;
	private ArrayList<MypoiItems> mypoiItems = new ArrayList<MypoiItems>();
	private int page_num = 1;
	private int max_page = 1;
	private GeoPoint point;
	private String poikey;
	private String poitype;
	private Favo favo;
	private Sqlh sqlh;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.poiresultlist);
		findView();

		Bundle bundle = this.getIntent().getExtras();
		sqlh = sqlh.getInstance(PoiList.this);
		poiString = bundle.getString("query_key");

		if (poiString != null && !poiString.equals("")) {
			dosearchpoi(page_num, 1);
		} else {
			//获取中心点的经纬度
			//和搜索类别及搜索关键字
			int lat = bundle.getInt("lat");
			int lon = bundle.getInt("long");
			Log.i("mylog",lat+"<--lat");
			point = new GeoPoint(lat, lon);
			poikey = bundle.getString("poikey");
			poitype = bundle.getString("poitype");
			dosearchpoi2(page_num, 1);
		}

		mAdapter = new MyAdapter();

		context = getApplicationContext();

		Log.i("mylog", "max_page:" + max_page + "classname:" + classname);

		poiListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent poIntent = new Intent();
				// 结果跳转到那个Activity

				poIntent = new Intent(PoiList.this, ShowMap.class);
				poIntent.putExtra("point_show", arg2);
				poIntent.putExtra("poilists", mypoiItems);
				startActivity(poIntent);

			}
		});

		next_but.setOnClickListener(nextpageListener);
		previous_but.setOnClickListener(prepageListener);

	}

	/**
	 * 
	 * 功能：执行单个关键字的poi搜索。
	 * 
	 * @param pagenum
	 *            搜索的页数
	 * @param type
	 *            上一页，下一页 void
	 */
	private void dosearchpoi(final int pagenum, final int type) {
		Thread t = new Thread(new Runnable() {
			public void run() {

				try {
					Log.i("mylog", "findCity()"+findCity());
					PoiSearch poiSearch = new PoiSearch(PoiList.this,
							new PoiSearch.Query(poiString, PoiTypeDef.All,
									findCity())); // 设置搜索字符串，"010为城市区号"
					
					result = poiSearch.searchPOI();
					max_page = result.getPageCount();

					Log.i("mylog", "max_page:" + max_page);
				} catch (AMapException e) {
					progDialog.dismiss();
					e.printStackTrace();
				}

				if (max_page > 0) {
					handler.obtainMessage(1, pagenum, type).sendToTarget();
				} else {
					handler.obtainMessage(0, pagenum, type).sendToTarget();

				}

			}
		});
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setIndeterminate(false);
		progDialog.setCancelable(true);
		progDialog.setMessage("正在搜索:  " + poiString + "\n请稍候！");
		progDialog.show();
		t.start();

	}

	/**
	 * 
	 * 功能：执行周边地区关键字的poi搜索。
	 * 
	 * @param pagenum
	 *            搜索的页数
	 * @param type
	 *            上一页，下一页 void
	 */
	private void dosearchpoi2(final int pagenum, final int type) {
		Thread t = new Thread(new Runnable() {
			public void run() {

				try {
					Log.i("mylog", "findCity()"+findCity());
					Log.i("mylog", poitype);
					PoiSearch poiSearch = new PoiSearch(PoiList.this,
							new PoiSearch.Query(poikey, poitype, findCity())); // 设置搜索字符串，"010为城市区号"
					poiSearch.setBound(new SearchBound(point, 1500));
					result = poiSearch.searchPOI();
					max_page = result.getPageCount();

					Log.i("mylog", "max_page:" + max_page);
				} catch (AMapException e) {
					progDialog.dismiss();
					e.printStackTrace();
				}

				if (max_page > 0) {
					handler.obtainMessage(1, pagenum, type).sendToTarget();
				} else {
					handler.obtainMessage(0, pagenum, type).sendToTarget();

				}

			}
		});
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setIndeterminate(false);
		progDialog.setCancelable(true);
		progDialog.setMessage("正在搜索:  " + poikey + "\n请稍候！");
		progDialog.show();
		t.start();

	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1 && msg.arg2 == 1) {
				try {

					mypoiItems.clear();
					poiItems = result.getPage(msg.arg1);
					// if (poiItems != null || poiItems.size() > 0) {
					if (poiItems != null) {
						Log.i("mylog", "" + poiItems.size());
						ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
						for (PoiItem poiItem : poiItems) {
							HashMap<String, String> poiMap = new HashMap<String, String>();
							poiMap.put("title", poiItem.getTitle());
							poiMap.put("snippet", poiItem.getSnippet());
							MypoiItems mpis = new MypoiItems();
							mpis.setId(poiItem.getPoiId());
							mpis.setTitle(poiItem.getTitle());
							mpis.setSnippet(poiItem.getSnippet());
							mpis.setLatit(poiItem.getPoint().getLatitudeE6());
							mpis.setLongit(poiItem.getPoint().getLongitudeE6());
							mypoiItems.add(mpis);
							listItem.add(poiMap);
						}

						poiListView.setAdapter(mAdapter);
						if (max_page > 1) {
							next_but.setEnabled(true);
						}
						if (max_page == page_num) {
							next_but.setEnabled(false);
						}
						poiListView.invalidate();
						progDialog.dismiss();

					}
				} catch (AMapException e) {

					Toast.makeText(getApplicationContext(), "网络连接错误！",
							Toast.LENGTH_SHORT).show();
					progDialog.dismiss();

				}
			} else if (msg.what == 1 && msg.arg2 == 0) {
				try {

					mypoiItems.clear();
					poiItems = result.getPage(msg.arg1);
					// if (poiItems != null || poiItems.size() > 0) {
					if (poiItems != null) {
						Log.i("mylog", "" + poiItems.size());
						ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
						for (PoiItem poiItem : poiItems) {
							HashMap<String, String> poiMap = new HashMap<String, String>();
							poiMap.put("title", poiItem.getTitle());
							poiMap.put("snippet", poiItem.getSnippet());
							MypoiItems mpis = new MypoiItems();
							mpis.setId(poiItem.getPoiId());
							mpis.setTitle(poiItem.getTitle());
							mpis.setSnippet(poiItem.getSnippet());
							mpis.setLatit(poiItem.getPoint().getLatitudeE6());
							mpis.setLongit(poiItem.getPoint().getLongitudeE6());
							mypoiItems.add(mpis);
							listItem.add(poiMap);
						}

						poiListView.setAdapter(mAdapter);

						if (msg.arg1 == 1) {
							previous_but.setEnabled(false);
						}
						poiListView.invalidate();
						progDialog.dismiss();

					}
				} catch (AMapException e) {

					Toast.makeText(getApplicationContext(), "网络连接错误！",
							Toast.LENGTH_SHORT).show();
					progDialog.dismiss();

				}
			} else if (msg.what == 0) {

				Toast.makeText(getApplicationContext(), "很遗憾没有搜到相关内容！",
						Toast.LENGTH_SHORT).show();
				progDialog.dismiss();
			}
		}
	};

	private void findView() {
		poiListView = (ListView) findViewById(R.id.poilist);
		previous_but = (Button) findViewById(R.id.prePage);
		next_but = (Button) findViewById(R.id.nextpage);
		progDialog = new ProgressDialog(this);

	}

	Button.OnClickListener nextpageListener = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			page_num++;
			if (poiString != null && !poiString.equals("")) {
				dosearchpoi(page_num, 1);
			} else {
				dosearchpoi2(page_num, 1);
			}
			previous_but.setEnabled(true);
		}
	};

	Button.OnClickListener prepageListener = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			page_num--;
			if (poiString != null && !poiString.equals("")) {
				dosearchpoi(page_num, 0);
			} else {
				dosearchpoi2(page_num, 0);
			}
			next_but.setEnabled(true);
		}
	};

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	public class MyAdapter extends BaseAdapter {
		MypoiItems myo = new MypoiItems();

		@Override
		public int getCount() {
			//
			return poiItems.size();
		}

		@Override
		public Object getItem(int arg0) {
			//
			return null;
		}

		@Override
		public long getItemId(int position) {
			//
			return 0;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			ViewHolder vHolder;

			if (convertView == null) {
				vHolder = new ViewHolder();
				LayoutInflater inflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.poiresult_c, parent,
						false);
				vHolder.poi_title = (TextView) convertView
						.findViewById(R.id.poi_name);
				vHolder.poi_snippet = (TextView) convertView
						.findViewById(R.id.poi_addr);
				vHolder.xiafa_button = (Button) convertView
						.findViewById(R.id.xf_but);
				vHolder.collcet_button = (Button) convertView
						.findViewById(R.id.collect_but);
				convertView.setTag(vHolder);

			} else {
				vHolder = (ViewHolder) convertView.getTag();
			}

			vHolder.poi_title.setText((String) poiItems.get(position)
					.getTitle());
			vHolder.poi_snippet.setText((String) poiItems.get(position)
					.getSnippet());

			vHolder.xiafa_button.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {

					Bundle bundle = new Bundle();
					bundle.putParcelable("poi_xf", mypoiItems.get(position));
					Intent intent = new Intent(PoiList.this, SendPosition.class);
					intent.putExtra("poi_xf", bundle);
					startActivity(intent);
				}
			});
			vHolder.collcet_button.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					favo = new Favo();
					favo.setFav_lat(mypoiItems.get(position).getLatit());
					favo.setFav_lon(mypoiItems.get(position).getLongit());
					favo.setFav_snipeet((String) poiItems.get(position)
							.getSnippet());
					favo.setFav_title((String) poiItems.get(position)
							.getTitle());
					favo.setJoin_date(new Tools().getnowtime());
					int noti = sqlh.add(favo);
					Log.i("mylog", "noti" + noti);
					showToast("地址已经收藏");
					
				}
			});

			return convertView;
		}
	}

	public final class ViewHolder {
		public Button xiafa_button;
		public Button collcet_button;
		public TextView poi_title;
		public TextView poi_snippet;
	}

	private String findCity() {
		SharedPreferences settings = getSharedPreferences(SPF,
				MODE_WORLD_READABLE);
		String cityString = settings.getString("city_now", "021");

		return cityString;

	}
	
	private void showToast(String showString) {
		Toast.makeText(getApplicationContext(), showString, Toast.LENGTH_SHORT)
				.show();
	}

}
